const express = require('express');
const router = express.Router();
const db = require('../utils/db')

router.get('/adminget', (req, res) => {

    const { search } = req.query;
    const sql = `select * from t_admin;`;
    const sql2 = `select count(*) as total from t_admin where a_name like '%${search}%';`;
    db.query(sql, (err, data) => {
        console.log(data);
        if (err) {
            res.json({ error: 1, msg: err });
        } else {
            db.query(sql2, (err2, data2) => {
                if (err2) {
                    res.json({ error: 1, msg: err2 });
                } else {
                    // console.log(data2)
                    res.json({ error: 0, data: data, total: data2[0].total });
                }
            })
        }
    })
})

router.post('/adminadd', (req, res) => {
    const { a_name, a_user, a_pass, type } = req.body;
    const sql = `insert into t_admin values(null,'${a_name}', ${a_user},${a_pass},'${type}')`
    db.query(sql, (err, data) => {
        if (err) {
            res.json({ error: 1, msg: err });
        } else {
            res.json({ error: 0, msg: '添加成功' });
        }
    })
})

/* 
url:/edit
data:{id,修改的字段}
method:post
res ;  {error:0,msg:'修改成功'} */
router.post('/adminEdit', (req, res) => {
    const { a_id, a_name, a_user, a_pass, a_status } = req.body;
    const sql = `update t_admin set a_name='${a_name}',a_user=${a_user},a_pass='${a_pass}',a_status='${a_status}' where a_id=${a_id}`

    db.query(sql, (err, data) => {
        if (err) {
            res.send({ error: 1, msg: err });
        } else {
            res.send({ error: 0, msg: '修改成功' });
        }
    })
})

// DELETE FROM `t_admin` WHERE (`a_id`='20')
router.post('/adminDel', (req, res) => {
    const { id } = req.body;
    const sql = `DELETE FROM t_admin WHERE a_id=${id}`
    db.query(sql, (err) => {
        if (err) {
            res.json({ error: 1, msg: err });
        } else {
            res.json({ error: 0, msg: '删除成功' });
        }
    })
})


module.exports = router;
/* 
    select * from user limit 起始，条数
    1页面显示5条

    1   0
    2   5
    3   10
    page  (page-1)*count
*/